import json
import logging
import datetime
from functools import wraps
from odoo.http import request, Response
from ..data_models.api_models import RPInterfaceModelForHeader as RPHeader
from ..data_models.api_models import RPInterfaceModelForResponse as RPResponse

_logger = logging.getLogger(__name__)


def default(o):
    """
    该函数的作用是将非JSON可序列化的对象转换为JSON可序列化对象
    json.dumps中default用于指定一个函数，用于序列化特殊数据类型的对象
    """
    if isinstance(o, (datetime.date, datetime.datetime)):
        return o.isoformat()
    if isinstance(o, bytes):
        return str(o)


def valid_response(data, status=200):
    """ 接口通畅，有效响应，正确业务 """
    rp_header = RPHeader(len(data))  # 创建响应头模型
    rp_response = RPResponse(status)  # 创建响应response模型
    data = {'response': rp_response.printf(),
            'data': data}
    return Response(json.dumps(data, ensure_ascii=False),
                    status=status,
                    headers=rp_header.printf())


def invalid_business(status=200, message_code=-1, message='', error_type='business'):
    """ 接口通畅，有效响应，错误业务 """
    rp_response = RPResponse(status, error_type, message_code, message)  # 创建响应response模型
    data = {'response': rp_response.printf()}
    rp_header = RPHeader(len(data))  # 创建响应头模型
    return Response(json.dumps(data, ensure_ascii=False),
                    status=status,
                    headers=rp_header.printf())


def invalid_response(status=200, message_code=-1, message='error', error_type='response'):
    """ 接口通畅，错误响应，未知业务 """
    rp_response = RPResponse(status, error_type, message_code, message)  # 创建响应response模型
    data = {'response': rp_response.printf(), }
    rp_header = RPHeader(len(data))  # 创建响应头模型
    return Response(json.dumps(data, ensure_ascii=False),
                    status=status,
                    headers=rp_header.printf())


def invalid_request(status=400, message_code=-1, message='', error_type='request'):
    """ 接口错误 """
    rp_response = RPResponse(status, error_type, message_code, message)  # 创建响应response模型
    data = {'response': rp_response.printf()}
    rp_header = RPHeader(len(data))  # 创建响应头模型
    return Response(json.dumps(data, ensure_ascii=False),
                    status=status,
                    headers=rp_header.printf())
